#!/bin/sh

#      Copyright (C) 2008-2017 Team XBMC
#      http://kodi.tv
#
#  This Program is free software; you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation; either version 2, or (at your option)
#  any later version.
#
#  This Program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with XBMC; see the file COPYING.  If not, write to
#  the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
#  http://www.gnu.org/copyleft/gpl.html

APP=@APP_NAME@
bin_name=@APP_NAME_LC@
SAVED_ARGS="$@"
prefix="@prefix@"
exec_prefix="@exec_prefix@"
datarootdir="@datarootdir@"
LIBDIR="@libdir@"
APP_BINARY=$LIBDIR/${bin_name}/@APP_BINARY@
CRASHLOG_DIR=${CRASHLOG_DIR:-$HOME}
KODI_DATA=${KODI_DATA:-"${HOME}/.${bin_name}"} # mapped to special://home/

# Workaround for high CPU load with nvidia GFX
export __GL_YIELD=USLEEP

# Fix wasting RAM due to fragmentation
export MALLOC_MMAP_THRESHOLD_=131072

# Check for some options used by this script
while [ "$#" -gt "0" ]
do
    case "$1" in
        --setlibdir)
            LIBDIR="$2"
            shift; shift
            ;;
        *)
            shift
            ;;
    esac
done

KODI_BINARY=${APP_BINARY}

if [ ! -x ${KODI_BINARY} ]; then
    echo "Error: ${KODI_BINARY} not found"
    exit 2
fi

APPORT_CORE="/var/crash/$(echo -n ${KODI_BINARY}|tr / _).$(id -u).crash"

command_exists()
{
  command -pv $1 >/dev/null 2>&1
}

single_stacktrace()
{
  # core filename is either "core.$PID" or "core"
  find "$1" -maxdepth $2 -name 'core*' | while read core; do
      LC_ALL=C gdb --core="$core" --batch 2> /dev/null | grep -q "^Core was generated by \`${KODI_BINARY}" || continue
      echo "=====>  Core file: "$core" ($(stat -c%y "$core"))" >> $FILE
      echo "        =========================================" >> $FILE
      gdb "${KODI_BINARY}" --core="$core" --batch -ex "thread apply all bt" 2> /dev/null >> $FILE
      rm -f "$core"
  done
}

print_crash_report()
{
  FILE="$CRASHLOG_DIR/${bin_name}_crashlog-`date +%Y%m%d_%H%M%S`.log"
  echo "############## $APP CRASH LOG ###############" >> $FILE
  echo >> $FILE
  echo "################ SYSTEM INFO ################" >> $FILE
  printf " Date: " >> $FILE
  date >> $FILE
  echo " $APP Options: $*" >> $FILE
  printf " Arch: " >> $FILE
  uname -m >> $FILE
  printf " Kernel: " >> $FILE
  uname -rvs >> $FILE
  printf " Release: " >> $FILE
  if [ -f /etc/os-release ]; then
	  . /etc/os-release
	  echo $NAME $VERSION >> $FILE
  elif command_exists lsb_release; then
    echo >> $FILE
    lsb_release -a 2> /dev/null | sed -e 's/^/    /' >> $FILE
  else
    echo "lsb_release not available" >> $FILE
  fi
  echo "############## END SYSTEM INFO ##############" >> $FILE
  echo >> $FILE
  echo "############### STACK TRACE #################" >> $FILE
  if command_exists gdb; then
    if command_exists systemd-coredumpctl; then
      systemd-coredumpctl dump -o core $(basename ${KODI_BINARY}) > /dev/null 2>&1
    elif command_exists coredumpctl; then
      coredumpctl dump -o core $(basename ${KODI_BINARY})  > /dev/null 2>&1
    elif command_exists apport-unpack && test -f "${APPORT_CORE}"; then
      TMP_DIR="$(mktemp -d -p ${HOME})"
      if [ -d "${TMP_DIR}" ]; then
        rm -f "${HOME}/core"
        apport-unpack "${APPORT_CORE}" "${TMP_DIR}"
        mv "${TMP_DIR}/CoreDump" "${HOME}/core"
        rm -rf "${TMP_DIR}"
      fi
    fi
    single_stacktrace "$PWD" 1
    # Find in plugins directories
    if [ $KODI_HOME ]; then
      BASEDIR=$KODI_HOME
    else
      BASEDIR="$LIBDIR/${bin_name}/"
    fi
    single_stacktrace "$BASEDIR" 5
    # find in userdata dir
    single_stacktrace "$HOME" 5
    # try /proc/sys/kernel/core_pattern
    # Check if it does not contain a pipe to a program (see man 5 core)
    if [ "$(cat /proc/sys/kernel/core_pattern | cut -c 1)" != "|" ]; then
      [ -d "$(dirname $(cat /proc/sys/kernel/core_pattern))" ] && single_stacktrace "$(dirname $(cat /proc/sys/kernel/core_pattern))" 1
    fi
  else
    echo "gdb not installed, can't get stack trace." >> $FILE
  fi
  echo "############# END STACK TRACE ###############" >> $FILE
  echo >> $FILE
  echo "################# LOG FILE ##################" >> $FILE
  echo >> $FILE
  if [ -f $KODI_TEMP/@APP_NAME_LC@.log ]
  then
    cat $KODI_TEMP/@APP_NAME_LC@.log >> $FILE
    echo >> $FILE
  elif [ -f $KODI_DATA/temp/@APP_NAME_LC@.log ]
  then
    cat $KODI_DATA/temp/@APP_NAME_LC@.log >> $FILE
    echo >> $FILE
  else
    echo "Logfile not found in the usual place." >> $FILE
    echo "Please attach it separately." >> $FILE
    echo "Use pastebin.com or similar for forums or IRC." >> $FILE
  fi
  echo >> $FILE
  echo "############### END LOG FILE ################" >> $FILE
  echo >> $FILE
  echo "############ END $APP CRASH LOG #############" >> $FILE
  echo "Crash report available at $FILE"
}

propagate_sigterm() {
  kill -TERM "$CHILD" 2>/dev/null
}

trap propagate_sigterm TERM

if command_exists gdb; then
  # Output warning in case ulimit is unsupported by shell
  eval ulimit -c unlimited
  if [ ! $? = "0" ]; then
    echo "${bin_name}: ulimit is unsupported by this shell" 1>&2
  fi
fi

ENV_ARGS=
if [ -n "${KODI_AE_SINK}" ]; then

  echo "KODI_AE_SINK env variable is deprecated and will be removed in the future."
  echo "Use the --audio-backend command line switch instead."

  if [ "${KODI_AE_SINK}" = "PIPEWIRE" ]; then
    ENV_ARGS="--audio-backend=pipewire"
  elif [ "${KODI_AE_SINK}" = "PULSE" ]; then
    ENV_ARGS="--audio-backend=pulseaudio"
  elif [ "${KODI_AE_SINK}" = "ALSA" ]; then
    ENV_ARGS="--audio-backend=alsa"
  elif [ "${KODI_AE_SINK}" = "OSS" ]; then
    ENV_ARGS="--audio-backend=oss"
  elif [ "${KODI_AE_SINK}" = "SNDIO" ]; then
    ENV_ARGS="--audio-backend=sndio"
  elif [ "${KODI_AE_SINK}" = "ALSA+PULSE" ]; then
    ENV_ARGS="--audio-backend=alsa+pulseaudio"
  fi
fi

if [ -n "${KODI_GL_INTERFACE}" ]; then

  echo "KODI_GL_INTERFACE env variable is deprecated and will be removed in the future."
  echo "Use the --gl-interface command line switch instead."

  if [ "${KODI_GL_INTERFACE}" = "GLX" ]; then
    ENV_ARGS="${ENV_ARGS} --gl-interface=glx"
  elif [ "${KODI_GL_INTERFACE}" = "EGL" ]; then
    ENV_ARGS="${ENV_ARGS} --gl-interface=egl"
  elif [ "${KODI_GL_INTERFACE}" = "EGL_PB" ]; then
    ENV_ARGS="${ENV_ARGS} --gl-interface=egl-pb"
  fi
fi

LOOP=1
while [ $(( $LOOP )) = "1" ]
do
  [ -f "${APPORT_CORE}" ] && rm -f "${APPORT_CORE}"
  LOOP=0
  ${KODI_BINARY} ${ENV_ARGS} $SAVED_ARGS &
  CHILD=$!
  wait "${CHILD}"
  RET=$?
  if [ $RET -eq 65 ]
  then # User requested to restart app
    LOOP=1
  elif [ $RET -ge 131 ] && [ $RET -le 136 ] || [ $RET -eq 139 ]
  then # Crashed with core dump
    print_crash_report
  fi
done

exit $RET
